package com.heima.article.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.exception.CustException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    private Configuration configuration;
    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    private String prefix;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    AuthorMapper authorMapper;
    /**
     * 生成文章静态页面
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            // 1 获取freemarker模板
            Template template = configuration.getTemplate("article.ftl");
            // 2 准备数据模型
            Map<String,Object> dataModel = new HashMap<>();
            // 2.1 文章详情
            dataModel.put("content",JSONArray.parse(content));
            // 2.2 文章信息
            dataModel.put("article",apArticle);
            // 2.3 文章作者的对应的userId
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            dataModel.put("authorApUserId",apAuthor.getUserId());
            // 3 使用数据替换模板  输出到 StringWriter
            StringWriter stringWriter = new StringWriter();
            template.process(dataModel,stringWriter);
            // 4 封装输入流 字节数组输入流
            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            // 5 将静态页内容上传到minio中
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            // 6 修改并保存文章static_url 静态页路径
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
            log.info("文章详情静态页面生成成功 staticUrl====> {}",path);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章详情静态页面生成失败 ==== 文章id是:{}   失败原因是:{}" ,apArticle.getId(),e.getCause());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文章详情静态页面生成失败");
        }
    }
}